package com.jxc.action.hygl;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javassist.expr.NewArray;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.aop.LogInfoAop;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VUser;
import com.jxc.service.MemberServiceI;
import com.jxc.service.MemberTypeServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ExportMember;
import com.jxc.util.ExportToExcel;
import com.jxc.util.ImportInfo;
import com.jxc.util.ImportMember;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/hygl")
@Action(value = "memberAction", results = {
		@Result(name = "member", location = "/member/member.jsp"),
		@Result(name = "memberTotal", location = "/member/memberTotal.jsp"),
		@Result(name = "memberAdd", location = "/member/memberAdd.jsp"),
		@Result(name = "memberEdit", location = "/member/memberEdit.jsp"),
		@Result(name = "saleRecord", location = "/member/saleRecord.jsp"),
		@Result(name = "memberImpExp", location = "/member/MemberImpExp.jsp"),
		@Result(name = "pointRecord", location = "/member/pointRecord.jsp"),
		@Result(name="doImport",location="/member/memberImport.jsp")})
public class MemberAction extends BaseAction implements ModelDriven<VMember> {
	private final static Logger logger = Logger.getLogger(MemberAction.class);
	@Autowired
	private MemberServiceI memberService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	
	@Autowired
	private MemberTypeServiceI memberTypeService;
	
	private VMember model = new VMember();
	
	private File file;	//文件上传使用的对象

	private String values;	//匹配的值
	
	public void setValues(String values) {
		this.values = values;
	}
	public String getValues() {
		return values;
	}
	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	@Override
	public VMember getModel() {
		return model;
	}

	public void setModel(VMember model) {
		this.model = model;
	}

	public String member() {
		getSubAuths("HYGL_HYGL");
		return "member";
	}
	
	public String memberTotal() {
		getSubAuths("SJTJ_HYTJ");
		return "memberTotal";
	}

	public String memberAdd() {
		return "memberAdd";
	}

	public String memberEdit() {
		return "memberEdit";
	}
	public String memberImpExp(){
		return "memberImpExp";
	}
	public void noAuth_combobox(){
		try {
			model.setSerial("");
			VUser vUser = userService.get(model.getUid());
			if(vUser.getReid()==null){
				model.setUid(vUser.getId());
			}else{
				model.setUid(vUser.getUpid());
			}
			super.writeJson(this.memberService.combobox(model));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void add() {
		Json j = new Json();
		try {
			model.setName(new URLDecoder().decode(model.getName(),"UTF-8"));
			model.setRemark(new URLDecoder().decode(model.getRemark(),"UTF-8"));
			//model.setAddress(new URLDecoder().decode(model.getAddress(),"UTF-8"));
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext
					.getRequest().getSession().getAttribute(
							ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() == null) {
				model.setUid(vuser.getId());
			} else {
				VRepertory vRepertory = repertoryService.get(vuser.getReid());
				model.setUid(vRepertory.getUid());
			}
			memberService.save(model);
			j.setObj(model);
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	@LogInfoAop(info = "编辑会员")
	public void edit() {
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext
					.getRequest().getSession().getAttribute(
							ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() == null) {
				model.setUid(vuser.getId());
			} else {
				VRepertory vRepertory = repertoryService.get(vuser.getReid());
				model.setUid(vRepertory.getUid());
			}
			memberService.update(model);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败！");
		}
		super.writeJson(j);
	}

	public void delete() {
		Json j = new Json();
		memberService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	public void datagrid() {
		try {
			/*SessionInfo sessionInfo = (SessionInfo) ServletActionContext
			.getRequest().getSession().getAttribute(
						ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() == null) {
				model.setUid(vuser.getId());
			} else {
				Long uid = repertoryService.getUidByReper(vuser.getId());
				model.setUid(uid);
			}
			super.writeJson(memberService.datagrid(model));*/
			DataGrid dg = new DataGrid();
			dg.setTotal(0l);
			dg.setRows(new ArrayList<VSalelist>());
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());	
			if (vuser.getReid() == null) {
				model.setUid(vuser.getId());
			} else {
				Long uid = repertoryService.getUidByReper(vuser.getId());
				model.setUid(uid);
			}			
			dg=memberService.datagrid(model);
			this.writeJson(dg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	//会员统计
	public void datagridTotal() {
		DataGrid dg = new DataGrid();
		dg.setTotal(0l);
		dg.setRows(new ArrayList<VSalelist>());
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUid(vuser.getUpid());

		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("repertory");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("consume");
		}
		dg=memberService.datagridTotal(model);
		this.writeJson(dg);
	}
	
	/**
	 * 获取会员统计数据后返回统计图给前端
	 * @return
	 * @throws Exception
	 */
	public String memberTotalChart() throws Exception {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUid(vuser.getUpid());
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("consume");
		}
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("repertory");
		}
		List<Object[]> vsls = memberService.memberTotal(model);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("image/jpeg");
		JFreeChart chart = memberService.getMemberTotalChart(vsls,model);
		ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 315, 240);
		return null;
	}
	
	public String saleRecord() {
		getRequest().setAttribute("serial",
				memberService.getMemberById(model.getId()).getSerial().trim());
		return "saleRecord";
	}

	public String pointRecord() {
		getRequest().setAttribute("serial",
				memberService.getMemberById(model.getId()).getSerial());
		return "pointRecord";
	}
	
	public void memberImp(){
		memberService.findImp();
	}
	
	/**
	 * 导出到excel
	 * @return
	 */
	public String export(){
		
		
		HttpServletResponse response=ServletActionContext.getResponse();
		HttpServletRequest request=ServletActionContext.getRequest();
		
		
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());
		
		//会员
		VMember vMember=new VMember();
		
		//获取指定经销商的数据
		if(vuser.getUpid()!=null){
			vMember.setUid(vuser.getUpid());
		}
		
		//得到列表
		List<VMember> vList=memberService.combobox(vMember);
		
		ExportMember em=new ExportMember(vList, "member.xls", request, response);
		
		try {
			
			em.export();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return null;
	}

	/**
	 * 导入数据到数据库
	 * @return
	 */
	public String doImport() throws Exception{
		
		ImportMember imp=(ImportMember)ServletActionContext.getRequest().getSession().getAttribute(ImportInfo.SESSOPM_SIGN);
		
		ActionContext req=ActionContext.getContext();
		
		boolean showRe=false;
		boolean showMe=false;
		
		//直接调用doSave 方法进行保存数据
		if(imp!=null&&this.values!=null){
			
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			imp.setValues(this.values);
			imp.setvUser(vuser);
			imp.setUserService(userService);
			imp.setRepertoryService(repertoryService);
			imp.setMemberTypeService(memberTypeService);
			
			//调用doSave 方法进行保存数据
			String sign=imp.doSave();
			
			
			ActionContext.getContext().put("success", imp.getSuccess());
			ActionContext.getContext().put("fail", imp.getFail());
			
			
			if(sign==ImportInfo.SUCCESS){
				//操作成功
				req.put("info", sign);
			}
			
			if(sign==ImportInfo.FAIL){
				req.put("info", sign);
			}
			
			//完成操作以后就从session清除该对象
			ServletActionContext.getRequest().getSession().removeAttribute(ImportInfo.SESSOPM_SIGN);
		}
		
		
		if(file!=null){
			
			//从session获取登录的经销商
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			
			ImportMember im=new ImportMember(file, ServletActionContext.getRequest(),memberService);
			im.setValues(this.values);
			im.setvUser(vuser);
			
			im.setUserService(userService);
			im.setRepertoryService(repertoryService);
			im.setMemberTypeService(memberTypeService);
			
			//先调用该方法才可以获取到相关的信息
			String sign=im.doImport();
	
			ActionContext.getContext().put("success", im.getSuccess());
			ActionContext.getContext().put("fail", im.getFail());
			
			
			
			
			
			
			//判断返回的标志进行相关的操作
			if(sign==ImportInfo.NOTSAME||sign==ImportInfo.MEMBER_REPERTORY){
				//会员类别数据差异
				
				//数据库的会员类别
				List<String> listA=im.getlA();
				req.put("listA", listA);
				
				String html="";
				boolean signs=true;
				for(String s:listA){
					if(signs){
						html+="'"+s+"':[]";
						signs=false;
					}else{
						html+=","+("'"+s+"':[]");
					}
				}
				req.put("html", html);
				//存在差异的
				List<String> listB=im.getNotSame();
				req.put("listB", listB);
				showMe=true;
				ActionContext.getContext().put("showMe", showMe);
				
				req.put("notsame",im.getRepertoryNotSame().size());
			}
			
			
//			//仓库	//暂时忽略
//			if(sign==ImportInfo.REPERTORY||sign==ImportInfo.MEMBER_REPERTORY){
//				
//				List<String> rList1=im.getRepertorys();
//				
//				String html="";
//				boolean signs=true;
//				for(String s:rList1){
//					if(signs){
//						html+="'"+s+"':[]";
//						signs=false;
//					}else{
//						html+=","+("'"+s+"':[]");
//					}
//				}
//				req.put("rebox", html);
//				
//				
//				List<String> rList2=im.getRepertoryNotSame();
//				
//				req.put("rList1", rList1);
//				req.put("rList2", rList2);
//				showRe=true;
//				
//				System.out.println("仓库匹配");
//				
//			}
			
			
		}
//		req.put("showRe", showRe);
		req.put("showMe", showMe);
		return "doImport";
	}
	
	
}
